if (select(2, UnitClass("player")) ~= "DRUID") then
	return -- Only load for druids
end

local Mod = LibStub("AceAddon-3.0"):NewAddon("ClassTimer Eclipse", "AceHook-3.0")

local cooldowns = { }
local spells = {
	{ spellid = 48517, cooldown = 30 },
	{ spellid = 48518, cooldown = 30 }
}
local currentCooldown

local function UnitDebuffHook(...)
	if currentCooldown == 0 then
		-- Get original data
		local name, rank, texture, count, debuffType, duration, endTime, caster, stealable = Mod.hooks.UnitDebuff(...)
		if name ~= nil then
			return name, rank, texture, count, debuffType, duration, endTime, caster, stealable
		end
	end
	
	-- When we get here, regular debuffs are finished, pull the next fake one
	local spell = cooldowns[currentCooldown]
	if spell then
		cooldowns[currentCooldown] = nil
		currentCooldown = currentCooldown + 1
		return spell.text, "", spell.icon, 0, nil, spell.cooldown, spell.lastExpiration, "player", nil
	end

	-- No more fake debuffs left, remove hook and return nil
	Mod:Unhook("UnitDebuff")
	return nil	
end

local function GetBuffsHook(self, unit, db)
	if unit == "player" then
		local currentTime = GetTime()
		local icon, duration, expTime
		local i = 0
		local spell
		
		for _, spell in ipairs(spells) do
			if spell.lastExpiration < currentTime then
				-- Not on cooldown (or not detected yet)
				_, _, icon, _, _, duration, expTime, _, _ = UnitBuff('player', spell.name)
				if icon == spell.icon and expTime ~= nil then
					-- Set it on cooldown
					spell.lastExpiration = expTime - duration + spell.cooldown
					cooldowns[i] = spell
					i = i + 1
				end
			else
				-- On cooldown
				cooldowns[i] = spell
				i = i + 1
			end
		end
		
		if i > 0 then
			-- cooldown, hook function
			Mod:RawHook("UnitDebuff", UnitDebuffHook, true)
			currentCooldown = 0
		end
		
	end
	-- Call original function
	Mod.hooks[ClassTimer].GetBuffs(self, unit, db)

end

function Mod:OnInitialize()
	local spell, name, icon
	for _, spell in ipairs(spells) do
		spell.name, _, spell.icon = GetSpellInfo(spell.spellid)
		spell.lastExpiration = 0
		spell.text = spell.name .. " (CD)"
	end
end

function Mod:OnEnable()
	self:RawHook(ClassTimer, "GetBuffs", GetBuffsHook)
	local spell
	for _, spell in ipairs(spells) do
		ClassTimer.db.profile.Abilities[spell.text] = true
	end
end

function Mod:OnDisable()
	self:UnhookAll()
	local spell
	for _, spell in ipairs(spells) do
		ClassTimer.db.profile.Abilities[spell.text] = nil
	end
end
